package cvi.com.reader.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnDismissListener;
import com.orhanobut.dialogplus.ViewHolder;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cvi.com.reader.R;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.adapter.PersonalDraftsAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.ChartDataBean;
import cvi.com.reader.bean.DeleteAllDraftDataListener;
import cvi.com.reader.bean.DraftDisplayDataListener;
import cvi.com.reader.bean.LoginBean;
import cvi.com.reader.bean.constant;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/30.
 * 草稿箱
 */

public class PersonalDraftsFragment extends BaseFragment implements PersonalDraftsAdapter.DeleteListener, DeleteAllDraftDataListener, PersonalDraftsAdapter.IssueListener {

    @BindView(R.id.gridview)
    MyGridView gridview;
    /* @BindView(R.id.delete_all)
     LinearLayout deleteAll;*/
    Unbinder unbinder;
    @BindView(R.id.no_data)
    TextView noData;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private String type;
    private List<ChartDataBean.DataBean> dataBeanList = new ArrayList<>();
    private PersonalDraftsAdapter personalDraftsAdapter = null;
    private DialogPlus deleteDialog;
    private DraftDisplayDataListener draftDisplayDataListener;
    private ChartDataBean.DataBean.UserBean userBean;
    private int sizeList=0;
    public DraftDisplayDataListener getDraftDisplayDataListener() {
        return draftDisplayDataListener;
    }

    public void setDraftDisplayDataListener(DraftDisplayDataListener draftDisplayDataListener) {
        this.draftDisplayDataListener = draftDisplayDataListener;
    }

    public MyGridView getGridview() {
        return gridview;
    }

    public void setGridview(MyGridView gridview) {
        this.gridview = gridview;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        type = bundle.getString("type");
        unbinder = ButterKnife.bind(this, super.onCreateView(inflater, container, savedInstanceState));
        initSmartRefreshLayout();
        Log.d("PersonalCollectFragment", "type222=" + type);
        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragemt_personal_drafts;

    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void initData() {
        getDraftsData();

    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dataBeanList.clear();
                initData();
            }
        });
    }

    //草稿箱
    private void getDraftsData() {
        dataBeanList.clear();
        NetWorkManager.getInstance().getNetWorkApiService().getPublicData(constant.DRAFTS).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        getData(response, "2");
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        smartRefreshLayout.finishRefresh(true);
                    }
                });
    }

    private void getData(JSONObject response, String type) {
        if (Hawk.contains("LoginBean")) {
            LoginBean loginBean = Hawk.get("LoginBean");
            userBean = new ChartDataBean.DataBean.UserBean();
            userBean.setAvatar(loginBean.getData().getUser_info().getAvatar());
            userBean.setRealname(loginBean.getData().getUser_info().getName());
            //  userBean.setId(loginBean.getMsg().getId());

        }
        JSONArray array = response.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);
            //将array中的数据进行逐条转换
            ChartDataBean.DataBean rowsBean = (ChartDataBean.DataBean) JSONObject.toJavaObject(object, ChartDataBean.DataBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            rowsBean.setUser(userBean);
            dataBeanList.add(rowsBean);
        }
        if (0 == dataBeanList.size()) {
            noData.setVisibility(View.VISIBLE);
            Log.d("sddddd", "我的草稿箱1111");
            draftDisplayDataListener.onDraftDisplay("0");
            smartRefreshLayout.setVisibility(View.GONE);
        } else {
            smartRefreshLayout.setVisibility(View.VISIBLE);
            noData.setVisibility(View.GONE);
            draftDisplayDataListener.onDraftDisplay("1");
        }
        personalDraftsAdapter = new PersonalDraftsAdapter(getActivity(), dataBeanList);
        gridview.setAdapter(personalDraftsAdapter);
        personalDraftsAdapter.setDeleteListener(this);
        personalDraftsAdapter.setIssueListener(this);
        personalDraftsAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initView() {
        stateView.getBackground().setAlpha(153);
    }

    @Override
    public void onDeleteClick(int id) {
        showDialog("0", id);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        PersonalActivity personalActivity = (PersonalActivity) activity;
        personalActivity.setDeleteAllDraftDataListener(this);
        draftDisplayDataListener = (DraftDisplayDataListener) getActivity();
    }

    private void deleteDrafts(int id,String flag) {

        NetWorkManager.getInstance().getNetWorkApiService().deleteDraftData(id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        if (flag.equals("1")) {
                            Log.d("sfdfdd", sizeList+"  "+dataBeanList.size());
                            if (sizeList==dataBeanList.size()){
                                sizeList=0;
                                getDraftsData();
                            }
                          //  personalDraftsAdapter.notifyDataSetChanged();

                        }else {
                            getDraftsData();

                        }

                        Toast.makeText(getActivity(), "删除成功！", Toast.LENGTH_LONG).show();
                    }
                });

    }

    private void deleteAllDrafts() {
        Log.d("wodefabu", "我的草稿箱删除" + type);
        NetWorkManager.getInstance().getNetWorkApiService().deleteAllDraftData().compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        dataBeanList.clear();
                        getDraftsData();
                        Toast.makeText(getActivity(), "删除全部成功！", Toast.LENGTH_LONG).show();
                    }
                });

    }

    private void showDialog(String flag, int id) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_delete, null);
        Button confirm = view.findViewById(R.id.confir_btn);
        Button cancel = view.findViewById(R.id.cancel_btn);
        TextView tv = view.findViewById(R.id.tips);
        if ("1".equals(flag)) {
            tv.setText("确定要全部删除吗？");
        } else if ("2".equals(flag)) {
            tv.setText("确定要发布作品吗？");
        } else {
            tv.setText("确定要删除吗？");
        }

        deleteDialog = DialogPlus.newDialog(getActivity())
                .setContentHolder(new ViewHolder(view))
                .setCancelable(true)
                .setGravity(Gravity.CENTER)
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogPlus dialog) {

                    }
                }).create();
        deleteDialog.show();
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(flag)) {

                    for (int i=0;i<dataBeanList.size();i++){
                        sizeList++;
                        deleteDrafts(dataBeanList.get(i).getId(),"1");
                    }

                } else if ("2".equals(flag)) {
                    IssueClick(id);
                } else {
                    deleteDrafts(id,"0");
                }

                deleteDialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteDialog.dismiss();
            }
        });
    }

    @Override
    public void onIssueClick(int id) {
        showDialog("2", id);
    }

    private void IssueClick(int id) {
        //发布作品
        NetWorkManager.getInstance().getNetWorkApiService().setIssue(id).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        dataBeanList.clear();
                        getDraftsData();
                        Toast.makeText(getActivity(), "发布成功！", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(constant.MYPUBLIC_MYRECEIVER);
                        getActivity().sendBroadcast(intent);      //发送广播
                    }
                });
    }

    @Override
    public void onDEleteAll(String flag) {
        showDialog("1", -1);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
